<template>
    <div class="app">
        <template  v-if="isSeach">
            <view class="top">
            <view class="back iconfont iconjiantou" @click="isSeach=false"></view>
            <view :class="['search-box',isSeach?'search-box1':'']">
                <view
                    v-if="!$util.isEmpty(currentRegion)"
                    @click="setCity"
                    class="region">
                    {{currentRegion[1]}}
                    <view :class="['triangle',isCity?'down':'']"></view>
                </view>
                <view class="shu"></view>
                <input @confirm="()=>confirmSeach()" v-model="seachKey" placeholder="请输入您的地址"/>
            </view>
            </view>
        </template>
        <!--关键词输入提示列表渲染-->
        <view class="add-list-box" v-if="isSeach">
            <scroll-view class="add-list" scroll-y>
                <view
                    v-for="(item,index) in seachListData"
                    :key="index"
                    @click="selectSeach(item,index)"
                    class="add-item">
                    <view>
                        <view class="title title1">{{item.title}}</view>
                        <view class="add add1">{{item.address}}</view>
                    </view>
                </view>
            </scroll-view>
        </view>
        <template v-if="!isSeach" >
            <div class="map-box">
                <map
                id="myMap"
                style="width: 100%; height: 300px;"
                :latitude="latitude" :longitude="longitude"
                @regionchange="mapChange">
                <cover-view class="top">
                    <cover-view class="back" @click="goBack">
                        <cover-image :src="`${constant.imgUrl}design/caseback.png`"></cover-image>
                    </cover-view>
                    <cover-view class="search-box">
                        <cover-view
                            v-if="!$util.isEmpty(currentRegion)"
                            class="region"
                            @click="setCity">
                            {{currentRegion[1]}}
                            <cover-view :class="['triangle',isCity?'down':'']"></cover-view>
                        </cover-view>
                        <cover-view class="shu"></cover-view>
                        <cover-view class="placeholder" @click="isSeach=true">请输入您的地址</cover-view>
                    </cover-view>
                </cover-view>
                <cover-view class="map-prompt">您可拖动地图, 标记地址位置</cover-view>
                <cover-image class="current-site-icon" :src="`${constant.imgUrl}common/marker.png`"></cover-image>
                <cover-view class="reload" @click="reload">
                    <cover-view class="center1">
                        <cover-view class="center2"></cover-view>
                    </cover-view>
                </cover-view>
                </map>
            </div>
            <scroll-view class="near-list" scroll-y>
                <view
                    v-for="(item,index) in nearListData"
                    :key="index"
                    @click="switchAddress(item,index)"
                    class="near-item">
                    <i
                        v-if="currentSelectAddress === index"
                        class="iconfont iconaddress current-site">
                    </i>
                    <view>
                        <view :class="['title',currentSelectAddress === index? 'title1':'']">{{item.title}}</view>
                        <view :class="['add',currentSelectAddress === index?'add1':'']" >{{item.address}}</view>
                    </view>
                </view>
            </scroll-view>
            <div class="confirm-address" @click="confirmAddress">
                确认地址
            </div>
        </template>
        <mapvueCityPicker
            @onCancel="onCancelCity"
            themeColor="#FFD11A"
            ref="mpvueCityPicker"
            :pickerValueDefault="[0,0,0]"
            @onConfirm="confirmCity" />
    </div>
</template>

<script>
/**
 * author fuwei
 *获取指定的参数值
 * @query {*}  url  指定回调页面及其他参数
 * 跳转回页面后带 addressInfo
 */
import appInputAll from '@/components/app_input_all'
import mapvueCityPicker from '@/components/mpvue-citypicker/mpvueCityPicker'
import { geocoder, suggestion } from '@/api/common/index'
export default {
	name: 'selectAddress',
	components: {
		appInputAll,
		mapvueCityPicker
	},
	data() {
		return {
			query: {},
			latitude: '',
			longitude: '',
			mapCtx: {},
			constant: this.$constant,
			address: '',
			isCity: false,
			currentRegion: [],
			isSeach: false,
			nearListData: [],
			seachListData: [],
			currentSelectAddress: 0,
			seachKey: ''
		}
	},
	onLoad(val) {
		this.mapCtx = uni.createMapContext('myMap')
		this.query = val
		this.reload()
	},
	methods: {
		goBack() {
			uni.navigateBack()
		},
		selectSeach(val, index) {
			this.currentRegion = [val.province, val.city, val.district]
			this.latitude = val.location.lat
			this.longitude = val.location.lng
			this.isSeach = false
			this.nearListData = this.seachListData
			this.currentSelectAddress = index
			this.seachListData = []
			this.seachKey = ''
		},
		confirmSeach(isCity = false) {
			suggestion({
				region: this.currentRegion[1],
				keyword: (isCity && !this.seachKey) ? this.currentRegion[1] : this.seachKey
			}).then(res => {
				if (!this.isSeach) {
					this.nearListData = res.data
					this.latitude = this.nearListData[0].location.lat
			        this.longitude = this.nearListData[0].location.lng
					return
				}
				this.seachListData = res.data
			})
		},
		setCity() {
			this.isCity = true
			this.$refs.mpvueCityPicker.show()
		},
		onCancelCity() {
			this.isCity = false
		},
		mapChange(e) {
			if (e.type == 'end' && (e.causedBy == 'scale' || e.causedBy == 'drag')) {
				this.mapCtx.getCenterLocation({
					success: (res) => {
						this.longitude = res.longitude
						this.latitude = res.latitude
						this.nearList()
					}
				})
			}
		},
		reload() {
			uni.getLocation({
				type: 'wgs84',
				success: (res) => {
					this.latitude = res.latitude
					this.longitude = res.longitude
					this.nearList()
				},
				// eslint-disable-next-line handle-callback-err
				fail: (err) => {
					uni.showToast({
						title: '定位失败',
						icon: 'none',
						duration: 1500
					})
					setTimeout(function() {
						uni.navigateBack({
							delta: 1
						})
					}, 1500)
				}

			})
		},
		confirmCity(val) {
			this.isCity = false
			this.currentRegion = val.label.split('-')
			this.confirmSeach(true)
		},
		nearList() {
			geocoder({
				latitude: this.latitude,
				longitude: this.longitude
			}).then(res => {
				console.log(res)
				let data = res.result
				this.currentSelectAddress = 0
				this.nearListData = data.pois
				this.currentRegion = [data.address_component.province, data.address_component.city, data.address_component.district]
			})
		},
		switchAddress(item, index) {
			this.currentSelectAddress = index
			this.latitude = item.location.lat
			this.longitude = item.location.lng
			if (!this.$util.isEmpty(item.province) && !this.$util.isEmpty(item.city)) {
				this.currentRegion = [item.province, item.city, item.district]
			}
		},
		confirmAddress() {
			const data = this.nearListData[this.currentSelectAddress]
			let from = {}
			if (!this.$util.isEmpty(data.ad_info)) {
				from = data.ad_info
			}
			let query = {
				...this.query,
				addressInfo: JSON.stringify({
					...data,
					...from
				})
			}
			if (this.query.url == 'addCS') {
        	let pages = getCurrentPages()// 获取页面栈
			 let prevPage = pages[pages.length - 2]// 上一个页面
			   if (prevPage) {
        		const { location, title, address, adcode } = JSON.parse(query.addressInfo)

					prevPage.$vm.form.map_longitude = location.lng
					prevPage.$vm.form.map_latitude = location.lat
					prevPage.$vm.form.short_address = title
					prevPage.$vm.form.full_address = address
					prevPage.$vm.adcode = adcode
					uni.navigateBack()
				}
			} else {
				uni.navigateTo({
				  url: `${this.query.url}${this.commonJS.queryData(query)}`
			  })
			}
		}
	}
}
</script>

<style lang="scss" scoped>
    .current-site-icon {
        width: 50px;
        height: 50px;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%,-50%);
}

.map-prompt {
  width: 420px;
  height: 60px;
  line-height: 60px;
  font-size: 24px;
  color: #707070;
  text-align: center;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0,0,0,0.1);
  position: absolute;
  bottom: 40px;
  left: 50%;
  transform: translate(-50%,0);
}
 .reload {
  width: 80px;
  height: 80px;
  background: #fff;
  border-radius: 50%;
  box-shadow: 0 0 10px rgba(0,0,0,0.1);
  position: absolute;
  bottom: 30px;
  right: 30px;
}
.reload .center1 {
  width: 30px;
  height: 30px;
  border: 1px solid #ffd11a;
  border-radius: 50%;
  margin: 24px auto;
}
.reload .center2 {
  width: 25px;
  height: 25px;
  background: #ffd11a;
  border-radius: 50%;
  margin: 3px auto;
}
.top {
  width: 100%;
  height: 80px;
  line-height: 80px;
  position: fixed;
  top: 0;
  left: 0;
  padding: 30px 20px;
  z-index: 999;
  overflow: hidden;
}
.back {
  width: 80px;
  height: 80px;
  line-height: 80px;
  color: #666;
  text-align: center;
  background: rgb(255,255,255);
  font-size: 50px;
  border-radius: 50%;
  float: left;
}
.back cover-image{
  width: 100%;
  height: 100%;
  display: inline-block;
}
.search-box {
  width: 610px;
  height: 80px;
  line-height: 80px;
  border-radius: 40px;
  background: rgb(255,255,255);
  margin-left: 20px;
  float: left;
  overflow: hidden;
  box-sizing: border-box;
}
.search-box1 {
  border: 1px solid #ccc;
  border-radius: 10px;
  background: #eee;
}
.search-box {
    box-sizing: border-box;
 & .region {
     box-sizing: border-box;
    width: 199px;
    line-height: 80px;
    font-size: 30px;
    color: #282828;
    text-align: center;
    float: left;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    padding-right: 35px;
    position: relative;
    & .triangle {
        width: 0;
        height: 0;
        border-left: 10px solid transparent;
        border-right: 10px solid transparent;
        border-top: 14px solid #000;
        position: absolute;
        right: 15px;
        top: 50%;
        transform: translate(0,-50%);
        z-index: 99999;
        &.down{
                border-top: none;
                border-bottom: 14px solid #000;
        }
    }
    }
}

.search-box .shu {
  width: 1px;
  height: 80px;
  background:#ccc;
  float: left;
}
.search-box input {
  width: 380px;
  height: 80px;
  line-height: 80px;
  font-size: 30px;
  color: #282828;
  padding: 10px 20px;
  box-sizing: border-box;
  float: left;
}
.search-box .placeholder{
  width: 380px;
  height: 80px;
  line-height: 80px;
  font-size: 30px;
  color: #ccc;
  padding: 0 20px;
  box-sizing: border-box;
  float: left;
}
.confirm-address {
    width: 80%;
    height: 90px;
    background-color: #ffd11a;
    margin: 0 auto;
    border-radius: 10px;
    line-height: 88px;
    text-align: center;
    position: fixed;
    bottom: 10px;
    left: 50%;
    transform: translate(-50%,0);
    font-size: 32px;
    color: #3a1b04;
}

.near-list {
  height: 650rpx;
  padding-bottom: 110rpx;
  box-sizing: border-box;
    .near-item {
    line-height: 40rpx;
    padding: 30rpx 50rpx 30rpx 90rpx;
    text-align: left;
    border-bottom: 1px solid #eee;
    position: relative;
    }
    .current-site {
        font-size: 40rpx;
        color: #3095F9;
        position: absolute;
        top: 40rpx;
        left: 30rpx;
    }
    .near-item .title {
    color: #282828;
    font-size: 32rpx;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    }
    .near-item .add {
    color: #707070;
    font-size: 24rpx;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    }
    .near-item .title1 {
    color: #3095F9;
    }
    .near-item .add1 {
    color: #3095F9;
    }
}
.add-list-box {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  z-index: 998;
  padding-top: 150rpx;
  background: #fff;
  box-sizing: border-box;
  overflow: hidden;
    .add-list {
  width: 100%;
  height: 1000rpx;
}
.add-item {
  line-height: 40rpx;
  padding: 30rpx 50rpx;
  text-align: left;
  border-top: 1px solid #eee;
}
.add-item .title {
  color: #282828;
  font-size: 32rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.add-item .add {
  color: #707070;
  font-size: 24rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.current-site-icon {
  width: 50rpx;
  height: 50rpx;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
}
}

.iconjiantou {
    transform: rotate(180deg);
}
</style>
